package org.yyjkcache.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * JSON处理器
 */
public class JsonHandler {
    private static JsonHandler handler = new JsonHandler();
    private static ObjectMapper mapper;

    private JsonHandler() {
        mapper = new ObjectMapper();
    }

    /**
     * json数组字符串转换为json字符串数组
     *
     * @param json
     * @return
     */
    public String[] toJsonArrayList(String json) {
        List<Object> list = null;
        String ailist[] = null;
        try {
            list = mapper.readValue(json, List.class);
            ailist = new String[list.size()];
            int index = 0;
            for (Object object : list) {
                ailist[index] = mapper.writeValueAsString(object);
                ++index;
            }
        } catch (IOException e) {
            e.printStackTrace();
            ailist=new String[1];
        }
        return ailist;
    }

    /**
     * 转换为list map 集合
     * @param json
     * @return
     */
    public List<Map<String,Object>>toMapCollection(String json){
        List<Map<String,Object>> list = null;
        try {
            list = mapper.readValue(json, List.class);

        } catch (IOException e) {
            e.printStackTrace();
            list=new ArrayList<>();
        }
        return  list;
    }

    /**
     * 返回处理器
     *
     * @return JsonHandler
     */
    public static JsonHandler handle() {
        return handler;
    }
}
